package com.click.app.webapp.action;

import com.click.app.model.AsignationCut;
import com.click.app.model.CutProcess;
import com.click.app.model.LabelValue;
import com.click.app.model.Material;
import com.click.app.model.PackageDetail;
import com.click.app.model.Purchase;
import com.click.app.model.PurchaseDetail;
import com.click.app.model.StorageCut;
import com.click.app.model.StorageMaterial;
import com.click.app.service.AsignationCutManager;
import com.click.app.service.CutProcessManager;
import java.util.Date;
import com.click.app.service.MaterialManager;
import com.click.app.service.PackageDetailManager;
import com.click.app.service.PurchaseDetailManager;
import com.click.app.service.StorageMaterialManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Joel Chuca
 * @date 24/04/2009
 */
public class PackageDetailAction extends BaseAction {

    private PackageDetailManager packageDetailManager;
    private PurchaseDetailManager purchaseDetailManager;
    private StorageMaterialManager storageMaterialManager;
    private List packageDetails;
    private PackageDetail packageDetail;
    private Long id;
    private Long idPurchaseDetail;
    private Material material;
    private Float currentQuantityUsed;
    private Float newQuantityUsed;
    private CutProcessManager cutProcessManager;
    private String code;
    private AsignationCutManager asignationCutManager;
    private MaterialManager materialManager;
    private List<StorageMaterial> storageMaterialList;
    private CutProcess cutProcess;
    List<Material> materials;
    List<StorageCut> storageCutList;

    private Map<String,String> packageDetailList;
    private String packageDetailChoice;

    private Long idPd;
    private AsignationCut asignationCut;
    private List<LabelValue> packDetListLabelValue;

    private String choicedPackDetRev;
    
    public void setPurchaseDetailManager(PurchaseDetailManager purchaseDetailManager) {
        this.purchaseDetailManager = purchaseDetailManager;
    }

    public void setPackageDetailManager(PackageDetailManager packageDetailManager) {
        this.packageDetailManager = packageDetailManager;
    }

    public void setMaterialManager(MaterialManager materialManager) {
        this.materialManager = materialManager;
    }

    public void setStorageMaterialManager(StorageMaterialManager storageMaterialManager) {
        this.storageMaterialManager = storageMaterialManager;
    }

    public PackageDetail getPackageDetail() {
        return packageDetail;
    }

    public void setPackageDetail(PackageDetail packageDetail) {
        this.packageDetail = packageDetail;
    }

    public List getPackageDetails() {
        return packageDetails;
    }

    public void setPackageDetails(List packageDetails) {
        this.packageDetails = packageDetails;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getIdPurchaseDetail() {
        return idPurchaseDetail;
    }

    public void setIdPurchaseDetail(Long idPurchaseDetail) {
        this.idPurchaseDetail = idPurchaseDetail;
    }

    public Material getMaterial() {
        return material;
    }

    public String list() {
        if (idPurchaseDetail != null) {
            PurchaseDetail purchaseDetail = purchaseDetailManager.get(idPurchaseDetail);
            getSession().setAttribute("purchaseDetail", purchaseDetail);
            packageDetails = purchaseDetail.getPackageDetails();
            material = purchaseDetail.getMaterial();
            getSession().setAttribute("material", material);

        } else {
            PurchaseDetail purchaseDetail = (PurchaseDetail) getSession().getAttribute("purchaseDetail");
            if (purchaseDetail != null) {
                packageDetails = purchaseDetailManager.get(purchaseDetail.getId()).getPackageDetails();
                material = (Material) getSession().getAttribute("material");
            } else {
                return "error";
            }
        }
        return SUCCESS;
    }

    public String edit() {

        System.out.println("edit()");
        String idp = ((PurchaseDetail) getSession().getAttribute("purchaseDetail")).getPurchase().getId().toString();
        String ps = ((Purchase) getSession().getAttribute("purchase")).getSupplier().getFullName();
        String pd = ((Purchase) getSession().getAttribute("purchase")).getDate().toString();
        String ptp = ((Purchase) getSession().getAttribute("purchase")).getTotalPrice().toString();
        String pm = ((PurchaseDetail) getSession().getAttribute("purchaseDetail")).getMaterial().getName();
        String pnp = ((Integer) ((PurchaseDetail) getSession().getAttribute("purchaseDetail")).getPackageDetails().size()).toString();

        getSession().setAttribute("idp", idp);
        getSession().setAttribute("ps", ps);
        getSession().setAttribute("pd", pd);
        getSession().setAttribute("ptp", ptp);
        getSession().setAttribute("pm", pm);
        getSession().setAttribute("pnp", pnp);

        material = (Material) getSession().getAttribute("material");
        if (id != null) {
            packageDetail = packageDetailManager.get(id);
        } else {
            packageDetail = new PackageDetail();
        }

        System.out.println("end edit()");
        return SUCCESS;

    }

    public String packageDetailReview(){
        System.out.println("packageDetailReview()");
        List<String> packDetailAux = packageDetailManager.getUniqueName();
        packDetListLabelValue = new ArrayList<LabelValue>();
        for (Iterator<String> it = packDetailAux.iterator(); it.hasNext();) {
            String name = it.next();
            packDetListLabelValue.add(new LabelValue(name,name));
        }
        System.out.println("end packageDetailReview()");
        return SUCCESS;
    }
    public String choicePackageDetailReview(){
        System.out.println("choicePackageDetailReview()");
        if(getSession().getAttribute("choicedPackDetRev") != null)
            choicedPackDetRev = (String) getSession().getAttribute("choicedPackDetRev");
        
        packageDetails = packageDetailManager.getByPackageName(choicedPackDetRev);
        getSession().setAttribute("choicedPackDetRev", choicedPackDetRev);
        System.out.println("end choicePackageDetailReview()");
        return SUCCESS;
    }
    public String editPackageDetailReview(){
        packageDetail = packageDetailManager.get(idPd);
        return SUCCESS;
    }
    public String editPackageDetailReviewRe(){
        asignationCut = asignationCutManager.get(idPd);
        packageDetail = asignationCut.getPackageDetail();
        return SUCCESS;
    }
    public String saveQuantFailPackageDetail(){
        System.out.println("saveQuantFailPackageDetail()");
        if( asignationCut.getQuantityUsedFail() == 0 ||
           (asignationCut.getQuantityUsedFail() > 0 && asignationCut.getPriceQuantUsedFail() > 0)){
           AsignationCut asignationCutAux = asignationCutManager.get(asignationCut.getId());
           asignationCutAux.setQuantityUsedFail(asignationCut.getQuantityUsedFail());
           asignationCutAux.setPriceQuantUsedFail(asignationCut.getPriceQuantUsedFail());
           asignationCutAux.setTotalQuantUsedFail(asignationCut.getQuantityUsedFail() * asignationCut.getPriceQuantUsedFail());
           asignationCutManager.save(asignationCutAux);
           saveMessage(getText("packageDetailAction.updated"));
           System.out.println("end saveQuantFailPackageDetail()");
           return SUCCESS;
        }else{
           errorMessage(getText("packageDetailAction.updated.error"));
           asignationCut = asignationCutManager.get(asignationCut.getId());
           System.out.println("end error saveQuantFailPackageDetail()");
           return ERROR;
        }
       
    }
    public String editPackageDetailRe(){
        asignationCut = asignationCutManager.get(idPd);
        return SUCCESS;
    }

    public String deletePackageDetail(){
        asignationCut = asignationCutManager.get(idPd);
        PackageDetail packageDetail = asignationCut.getPackageDetail();
        CutProcess cutProcess = asignationCut.getCutProcess();
        packageDetail.setStock(packageDetail.getStock()+ asignationCut.getQuantityUsed());
        StorageMaterial storageMaterial = packageDetail.getStorageMaterial();
        storageMaterial.incrementStok(asignationCut.getQuantityUsed());
        storageMaterialManager.save(storageMaterial);
        packageDetailManager.save(packageDetail);
        asignationCutManager.remove(idPd);
        return SUCCESS;
    }
    public String save() {
        System.out.println("--------- Start Save (PackageDetailAction) ----------- ");

        if (cancel != null) {
            return CANCEL;
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = false;

        isNew = (packageDetail.getId() == null);

        packageDetail.setStock(packageDetail.getQuantity());
        PurchaseDetail purchaseDetail = (PurchaseDetail) getSession().getAttribute("purchaseDetail");
        material = (Material) getSession().getAttribute("material");
        packageDetail.setPurchaseDetail(purchaseDetail);
        packageDetail.setStorageMaterial(material.getStorageMaterial());
        packageDetail.setCode(code);
        if (isNew) {
            System.out.println("saving with code: " + getUCode());
            packageDetail.setId(getUCode());
        }
        if ((packageDetail.getQuantity()+purchaseDetail.getPackagesTotal())>purchaseDetail.getQuantity()){
            errorMessage("Solamente puede asignar una cantidad de: "+(purchaseDetail.getQuantity()-purchaseDetail.getPackagesTotal())+" como máximo");
            return ERROR;
        }
        packageDetail = packageDetailManager.save(packageDetail);
        purchaseDetail.getPackageDetails().add(packageDetail);

        System.out.println("--------- End Save (PackageDetailAction) ----------------");
        if (isNew) {
            saveMessage(getText("packageDetail.added"));
            return SUCCESS;
        } else {
            saveMessage(getText("purchaseDetail.updated"));
            return INPUT;
        }
    }

    public String delete() {
        packageDetailManager.remove(packageDetail.getId());
        PurchaseDetail pd = (PurchaseDetail) getSession().getAttribute("purchaseDetail");
        pd.getPackageDetails().remove(packageDetail);
        getSession().setAttribute("purchaseDetail", pd);

        saveMessage(getText("purchaseDetail.deleted"));

        return SUCCESS;
    }

    public String addPackageDetail() {
        if(id == null )
            id = (Long)getSession().getAttribute("idCutProcess");
        
        List<String> packDetailAux = packageDetailManager.getUniqueName();
        packageDetailList = new HashMap<String,String>();
        for (Iterator<String> it = packDetailAux.iterator(); it.hasNext();) {
            String name = it.next();
            packageDetailList.put(name, name);
        }
        cutProcess = cutProcessManager.get(id);
        return SUCCESS;
    }

    public String addQuantityPackageDetail(){
        System.out.println("addQuantityPackageDetail()");
        packageDetail = packageDetailManager.get(idPd);
        System.out.println("end addQuantityPackageDetail()");
        return SUCCESS;
    }
    public String saveAddQuantPackageDetail(){
        System.out.println("saveAddQuantPackageDetail()");
        Long idCutPocess = (Long) getSession().getAttribute("idCutProcess");

        CutProcess cutProcess = cutProcessManager.get(idCutPocess);
        PackageDetail packageDetailAux = packageDetailManager.get(packageDetail.getId());
        
        if (packageDetailAux.getStock() >= newQuantityUsed) {
            packageDetailAux.setStock(packageDetailAux.getStock() - newQuantityUsed);

            AsignationCut asignationCut = new AsignationCut();
            asignationCut.setPackageDetail(packageDetailAux);
            asignationCut.setCutProcess(cutProcess);
            asignationCut.setQuantityUsed(newQuantityUsed);

            asignationCutManager.save(asignationCut);
            packageDetailManager.save(packageDetailAux);

            StorageMaterial storageMaterial = packageDetailAux.getStorageMaterial();
            storageMaterial.decrementStok(newQuantityUsed);
            storageMaterialManager.save(storageMaterial);
            System.out.println("end saveAddQuantPackageDetail()");
            id = idCutPocess;
            return SUCCESS;
         }else{
                return ERROR;
            }
    }
    public String packageDetailsChoice(){
        System.out.println("packageDetailsChoice()");
        List<String> packDetailAux = packageDetailManager.getUniqueName();
        packageDetailList = new HashMap<String,String>();
        for (Iterator<String> it = packDetailAux.iterator(); it.hasNext();) {
            String name = it.next();
            packageDetailList.put(name, name);
        }
        if( getSession().getAttribute("packageDetailChoice") != null)
            packageDetailChoice = (String)getSession().getAttribute("packageDetailChoice");
        packageDetails = packageDetailManager.getByPackageNameAndRealQuantNoCero(packageDetailChoice);
        getSession().setAttribute("packageDetailChoice", packageDetailChoice);
        cutProcess = cutProcessManager.get((Long)getSession().getAttribute("idCutProcess"));
        System.out.println("end packageDetailsChoice()");
        return SUCCESS;
    }

    public String donePackageDetailReview(){
        return SUCCESS;
    }

    public String cancelPackageDetailReview(){
        return SUCCESS;
    }
    public String savePackageDetailReview() {
        System.out.println("savePackageDetailReview()");
        if(packageDetail.getRealQuantity() > 0){
            PackageDetail packageDetailAux = packageDetailManager.get(packageDetail.getId());
            Float incr = packageDetail.getRealQuantity() - packageDetailAux.getQuantity();
            packageDetailAux.setStock(packageDetailAux.getStock() + incr);
            if(packageDetailAux.getRealQuantity() <=0 ){
                packageDetailAux.setRealQuantity( packageDetail.getRealQuantity());
            }else{
                packageDetailAux.setRealQuantity(packageDetailAux.getRealQuantity() + incr);
            }

            packageDetailManager.save(packageDetailAux);

            StorageMaterial storageMaterial = packageDetailAux.getStorageMaterial();
            storageMaterial.setStock(storageMaterial.getStock() + incr);
            storageMaterialManager.save(storageMaterial);
            System.out.println("End savePackageDetailReview()");

                return SUCCESS;
            
        }
        return ERROR;
    }        

    public Float getCurrentQuantityUsed() {
        return currentQuantityUsed;
    }

    public void setCurrentQuantityUsed(Float currentQuantityUsed) {
        this.currentQuantityUsed = currentQuantityUsed;
    }

    public Float getNewQuantityUsed() {
        return newQuantityUsed;
    }

    public void setNewQuantityUsed(Float newQuantityUsed) {
        this.newQuantityUsed = newQuantityUsed;
    }

    public AsignationCutManager getAsignationCutManager() {
        return asignationCutManager;
    }

    public void setAsignationCutManager(AsignationCutManager asignationCutManager) {
        this.asignationCutManager = asignationCutManager;
    }

    public CutProcessManager getCutProcessManager() {
        return cutProcessManager;
    }

    public void setCutProcessManager(CutProcessManager cutProcessManager) {
        this.cutProcessManager = cutProcessManager;
    }

    /**
     * @return the code
     */
    public String getCode() {
        Date date = new Date();
        int d1 = date.getDate();
        int m1 = date.getMonth();
        int y1 = date.getYear();
        int m2 = m1 + 1;
        int y2 = y1 + 1900;

        PurchaseDetail pd = (PurchaseDetail) getSession().getAttribute("purchaseDetail");
        Integer i = pd.getPackageDetails().size();
        Integer ind=0;
        if (pd.getPackageDetails()!=null && !pd.getPackageDetails().isEmpty()){
        String lastCode  = pd.getPackageDetails().get(pd.getPackageDetails().size()-1).getCode();
        Character in = lastCode.charAt(lastCode.length()-1);
        System.out.println("IN:"+in);
        ind = new Integer(in.toString());
        System.out.println("IND:"+ind);
        }

        if (packageDetail != null) {
            code = packageDetail.getCode();
        }
        if (code == null) {
            code = "cod" + "-" + "paq" + "-" + (getUCode()) + "-" + (date.getDate()) + "-" + (m2) + "-" + (y2) + "-" + (ind+1);
        }

        System.out.println("code: " + code);
        return code;
    }

    /**
     * @param code the code to set
     */
    public void setCode(String code) {
        this.code = code;
    }

    public List<LabelValue> getNames() {
        List<LabelValue> names = new ArrayList<LabelValue>();
        names.add(new LabelValue("rollo", "rollo"));
        names.add(new LabelValue("caja", "caja"));
        return names;
    }

    public Long getUCode() {
        PurchaseDetail pd = (PurchaseDetail) getSession().getAttribute("purchaseDetail");
        return pd.getId();
    }

    public List<Material> getMaterials() {
        return materials;
    }

    public void setMaterials(List<Material> materials) {
        this.materials = materials;
    }

    public List<StorageCut> getStorageCutList() {
        return storageCutList;
    }

    public void setStorageCutList(List<StorageCut> storageCutList) {
        this.storageCutList = storageCutList;
    }

    public List<StorageMaterial> getStorageMaterialList() {
        return storageMaterialList;
    }

    public void setStorageMaterialList(List<StorageMaterial> storageMaterialList) {
        this.storageMaterialList = storageMaterialList;
    }

    public CutProcess getCutProcess() {
        return cutProcess;
    }

    public void setCutProcess(CutProcess cutProcess) {
        this.cutProcess = cutProcess;
    }

    public String getPackageDetailChoice() {
        return packageDetailChoice;
    }

    public void setPackageDetailChoice(String packageDetailChoice) {
        this.packageDetailChoice = packageDetailChoice;
    }

    public Map<String, String> getPackageDetailList() {
        return packageDetailList;
    }

    public void setPackageDetailList(Map<String, String> packageDetailList) {
        this.packageDetailList = packageDetailList;
    }

    public Long getIdPd() {
        return idPd;
    }

    public void setIdPd(Long idPd) {
        this.idPd = idPd;
    }

    public AsignationCut getAsignationCut() {
        return asignationCut;
    }

    public void setAsignationCut(AsignationCut asignationCut) {
        this.asignationCut = asignationCut;
    }

    public List<LabelValue> getPackDetListLabelValue() {
        return packDetListLabelValue;
    }

    public void setPackDetListLabelValue(List<LabelValue> packDetListLabelValue) {
        this.packDetListLabelValue = packDetListLabelValue;
    }

    public String getChoicedPackDetRev() {
        return choicedPackDetRev;
    }

    public void setChoicedPackDetRev(String choicedPackDetRev) {
        this.choicedPackDetRev = choicedPackDetRev;
    }


}